package random.fox.p2p.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import random.fox.p2p.AppConfig;

/**
 * 工具类
 * Created by wq on 15/3/19.
 */
public class Util {
    private Util() {
    }

    private static String TAG = "Util";
    private static final int MEDIA_TYPE_IMAGE = 1;
    private static final int MEDIA_TYPE_VIDEO = 2;
    /**
     * 用来接受返回的数据的静态字段,相机拍照
     */
    public static final int CAMERA = 10;
    /**
     * 用来接受返回的数据的静态字段,图库选图片
     */
    public static final int GALLERY = 8;
    /**
     * 裁剪图片
     */
    public static final int CROP = 9;

    /**
     * 校验手机号,只有是1开头的11位数
     *
     * @param number
     * @return
     */
    public static boolean isPhoneNumber(String number) {
        if (TextUtils.isEmpty(number))
            return false;

        if (number.matches("[1]\\d{10}"))
            return true;

        return false;
    }

    /**
     * 校验密码,6到16位 字母，数字，下划线 密码
     *
     * @param password
     * @return
     */
    public static boolean checkPassword(String password) {
        if (TextUtils.isEmpty(password))
            return false;

        if (password.matches("[_a-zA-Z\\d+]{6,16}"))
            return true;

        return false;
    }

    /**
     * 昵称是否符合规则
     *
     * @param nickName
     * @return
     */
    public static boolean checkNickName(String nickName) {
        if (TextUtils.isEmpty(nickName))
            return false;
        //TODO 昵称的校验规则设置
        return true;
    }

    /**
     * 生日日期格式是否正确的校验
     *
     * @param birthday
     * @return
     */
    public static boolean checkBirthday(String birthday) {
        if (TextUtils.isEmpty(birthday))
            return false;
        //TODO 昵称的校验规则设置
        return true;
    }

    /**
     * 调用相机拍照到指定位置
     *
     * @param context 必须是Activity
     * @param fileUri 用于存放拍照结果
     */
    public static void getPicByCamera(Activity context, Uri fileUri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        context.startActivityForResult(intent, CAMERA);
    }

    /**
     * 调用图库获取图片
     *
     * @param context 必须是Activity
     */
    public static void getPicByGallery(Activity context) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        context.startActivityForResult(intent, GALLERY);
    }

    /**
     * 只提供拍摄图片了
     *
     * @return
     */
    public static Uri getOutputMediaFileUri() {
        return Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE));
    }

    /**
     * 生成的图片应该是在/sdcard/Pictures/p2p 下面
     *
     * @param type
     * @return
     */
    private static File getOutputMediaFile(int type) {

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), AppConfig.CACHE_DIR);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "failed to create directory");
                return null;
            } else {
                File file = new File(mediaStorageDir.getPath() + "/.nomedia");//用来屏蔽相册读取
                if (!file.exists())
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }
        return mediaFile;
    }

    /**
     * 通过下列参数切图
     *
     * @param aspectX 方框宽
     * @param aspectY 方框高
     * @param outputX 输出图宽
     * @param outputY 输出图高
     * @param uri     被切的图的uri
     */
    public static void cropPic(Activity activity,
                               int aspectX, int aspectY, int outputX, int outputY,
                               Uri uri, Uri cropUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false); // no face detection
        activity.startActivityForResult(intent, CROP);
    }

    /**
     * 通过下列参数切图
     *
     * @param uri     被切的图的uri
     */
    public static void cropPicDefault(Activity activity,
                               Uri uri, Uri cropUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false); // no face detection
        activity.startActivityForResult(intent, CROP);
    }

    /**
     * 通过uri获得File
     *
     * @return
     */
    public static File getFileFromUri(Context context, Uri uri) {
        if (uri == null)
            return null;

        File file = null;
        String scheme = uri.getScheme();
        if ("file".equals(scheme)) {
            file = new File(uri.getPath());
        } else if ("content".equals(scheme)) {
            String[] proj = {MediaStore.Images.Media.DATA};
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = resolver.query(uri, proj, null, null, null);
            int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String img_path = cursor.getString(actual_image_column_index);
            cursor.close();

            file = new File(img_path);
        }

        if (file != null && !file.exists()) //file不存在
            file = null;

        return file;
    }

    /**
     * 执行一个shell命令，并返回字符串值
     *
     * @param cmd
     * 命令名称&参数组成的数组（例如：{"/system/bin/cat", "/proc/version"}）
     * @param workdirectory
     * 命令执行路径（例如："system/bin/"）
     * @return 执行结果组成的字符串
     * @throws IOException
     */
    public static synchronized String run(String[] cmd, String workdirectory)
            throws IOException {
        StringBuffer result = new StringBuffer();
        try {
            // 创建操作系统进程（也可以由Runtime.exec()启动）
            // Runtime runtime = Runtime.getRuntime();
            // Process proc = runtime.exec(cmd);
            // InputStream inputstream = proc.getInputStream();
            ProcessBuilder builder = new ProcessBuilder(cmd);

            InputStream in = null;
            // 设置一个路径（绝对路径了就不一定需要）
            if (workdirectory != null) {
                // 设置工作目录（同上）
                builder.directory(new File(workdirectory));
                // 合并标准错误和标准输出
                builder.redirectErrorStream(true);
                // 启动一个新进程
                Process process = builder.start();

                // 读取进程标准输出流
                in = process.getInputStream();
                byte[] re = new byte[1024];
                while (in.read(re) != -1) {
                    result = result.append(new String(re));
                }
            }
            // 关闭输入流
            if (in != null) {
                in.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result.toString();
    }

    public static String times(Date begin, Date end) {
        long between = 0;
        try {
            between = (end.getTime() - begin.getTime());// 得到两者的毫秒数
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        long day = between / (24 * 60 * 60 * 1000);
        long hour = (between / (60 * 60 * 1000) - day * 24);
        long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
        if (day > 0) {
            return day + "天前";
        } else if (hour > 0) {
            return hour + "小时前";
        } else if (min > 0) {
            return min + "分钟前";
        } else {
            return "刚刚";
        }
    }


}
